package com.cloudkinto.controller.order;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudkinto.base.BaseController;
import com.cloudkinto.bo.order.OrderVdfQueryBo;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.StringsUtil;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.service.order.OrderAmazonVdfService;
import com.cloudkinto.service.order.vo.Export2ShipOrderReq;
import com.cloudkinto.service.orderoutput.vo.OrderOutputAddReq;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>
 * 亚马逊供应商api订单 前端控制器
 * </p>
 *
 * @author ding
 * @since 2024-06-19
 */
@RestController
@Api(tags = "亚马逊供应商api订单模块")
@RequestMapping("/api/OrderAmazonVendor")
public class OrderAmazonVdfController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(OrderAmazonVdfController.class);

    @Autowired
    private OrderAmazonVdfService orderAmazonVdfService;

    @UserSessionRequired
    @PostMapping("")
    @ApiOperation(value = "亚马逊供应商api订单新增", notes = "亚马逊供应商api订单新增")
    public SingleResult add(@RequestBody @Validated Object req) {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return SingleResult.success("新增成功", orderAmazonVdfService.add(req, userId));
    }

    @UserSessionRequired
    @PutMapping("")
    @ApiOperation(value = "亚马逊供应商api订单修改", notes = "亚马逊供应商api订单修改")
    public SingleResult update(@RequestBody @Validated Object req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功", orderAmazonVdfService.update(req, userId));
    }

    @UserSessionRequired
    @DeleteMapping("/{id}")
    @ApiOperation(value = "亚马逊供应商api订单根据id删除", notes = "亚马逊供应商api订单根据id删除")
    public SingleResult delete(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success("删除成功", orderAmazonVdfService.delete(id, userId));
    }

    @UserSessionRequired
    @GetMapping("/{id}")
    @ApiOperation(value = "亚马逊供应商api订单根据id查看详情", notes = "亚马逊供应商api订单根据id查看详情")
    public SingleResult detail(@PathVariable("id") Long id) {
        return SingleResult.success("查询成功", orderAmazonVdfService.detail(id));
    }

    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiOperation(value = "亚马逊供应商api订单查询（分页）", notes = "亚马逊供应商api订单查询（分页）")
    public PageResult listPage(OrderVdfQueryBo bo) {
        Long companyId = getCompanyId();
        if (companyId != null) {
            bo.setCompanyId(companyId);
        }
        return orderAmazonVdfService.getListPage(bo);
    }

    @UserSessionRequired
    @PostMapping("mark/sendOut")
    @ApiOperation(value = "标记为发货", notes = "标记为发货")
    public SingleResult markSendOut(@RequestBody List<Long> ids) throws Exception {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return orderAmazonVdfService.markSendOut(ids, userId);
    }
//
//     @UserSessionRequired
//     @PutMapping("systemMemo")
//     @ApiOperation(value = "编辑系统备注", notes = "")
//     public SingleResult systemMemo(@RequestBody @Validated UpdateSysMemoReq req) throws Exception {
//         Long userId = getCurrentUserId();
//         Long companyId = getCompanyId();
//         return service.updateSysMemo(req, userId, companyId);
//     }
//

    @UserSessionRequired
    @PostMapping("sendOut")
    @ApiOperation(value = "发货", notes = "发货")
    public SingleResult sendOut(@RequestBody Export2ShipOrderReq req) throws Exception {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        if (req.getIsSolo() == 0) {
            return orderAmazonVdfService.sendOut(req.getOrderids(), userId, companyId, false);
        } else {
            return orderAmazonVdfService.sendOutNopackage(req.getOrderids()[0], userId, companyId);
        }
    }

    @UserSessionRequired
    @PostMapping("sendOutMatch")
    @ApiOperation(value = "确认发货发货", notes = "确认发货发货")
    public SingleResult sendOutMatch(@RequestBody List<OrderOutputAddReq> orderOutputAddReqList) throws Exception {
        Long userId = getCurrentUserId();
        return orderAmazonVdfService.sendOutMatch(orderOutputAddReqList, userId);
    }

    /*@PostMapping("/testOrder")
    public void test(@RequestBody String str){
        List<VendorOrderEntity> vcOrderList = JSONArray.parseArray(
                str,
                VendorOrderEntity.class
        );
        orderAmazonVdfService.insertVdf(vcOrderList,1L,1L);
    }*/
    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return orderAmazonVdfService.pageInit(getCompanyId());
    }

    //    @UserSessionRequired
    @GetMapping("/syncOrderByShop")
    @ApiOperation(value = "同步订单", notes = "同步订单")
    public SingleResult syncOrder(Long id, String beforeDate, String afterDate) {
        if (Objects.isNull(id)) {
            throw new BizException(SysConstant.Vdf_Order_Sync_Missing_Shop_Id);
        }
        Date before, after;
        if (StringUtils.isEmpty(beforeDate) || StringUtils.isEmpty(afterDate)) {
            // 默认查询7天
            before = DateUtils.passingDate(new Date(), -7);
            after = new Date();
        } else {
            before = DateUtil.parse(beforeDate);
            after = DateUtil.parse(afterDate);
        }
        orderAmazonVdfService.vdfOrderSync(id, before, after);
        return SingleResult.success(StringsUtil.createI18Message(SysConstant.Geting_Shipping_Label), null);
    }

    @GetMapping("/getCustomerInvoices")
    @ApiOperation(value = "同步客户发票", notes = "同步客户发票")
    public SingleResult getCustomerInvoices(Long id, String beforeDate, String afterDate) {
        if (Objects.isNull(id)) {
            throw new BizException(SysConstant.Customer_Invoices_Sync_Missing_Shop_Id);
        }
        Date before, after;
        if (StringUtils.isEmpty(beforeDate) || StringUtils.isEmpty(afterDate)) {
            // 默认查询7天
            before = DateUtils.passingDate(new Date(), -7);
            after = new Date();
        } else {
            before = DateUtil.parse(beforeDate);
            after = DateUtil.parse(afterDate);
        }
        orderAmazonVdfService.getCustomerInvoices(id, before, after);
        return SingleResult.success();
    }

    @UserSessionRequired
    @GetMapping("/exportShippingLabelPdf")
    @ApiOperation(value = "导出PDF", notes = "导出PDF")
    public void exportShippingLabelPdf(Long[] ids, HttpServletResponse response) {
        orderAmazonVdfService.exportShippingLabelVerticalA5Pdf(Arrays.asList(ids), response);
    }

    @UserSessionRequired
    @PostMapping("/createShippingLabel")
    @ApiOperation(value = "生成面单", notes = "生成面单")
    public SingleResult createShippingLabel(@RequestBody JSONObject param) {
        JSONArray purchaseOrderNumberList = param.getJSONArray("purchaseOrderNumberList");
        return SingleResult.success(
                orderAmazonVdfService.createShippingLabelV2(
                        purchaseOrderNumberList.toJavaList(String.class),
                        false
                )
        );
    }

    @UserSessionRequired
    @PutMapping("/modifyShippingLabel/{purchaseOrderNumber}")
    @ApiOperation(value = "重新分包", notes = "重新分包")
    public SingleResult modifyShippingLabel(@PathVariable String purchaseOrderNumber) {
        return SingleResult.success(
                orderAmazonVdfService.createShippingLabelV2(
                        Collections.singletonList(purchaseOrderNumber),
                        true
                )
        );
    }

    @UserSessionRequired
    @ApiOperation(value = "刷新分包信息", notes = "刷新分包信息")
    @GetMapping("/refreshShippingLabel/{purchaseOrderNumber}")
    public SingleResult refreshShippingLabel(@PathVariable String purchaseOrderNumber) {
        return SingleResult.success(
                orderAmazonVdfService.refreshShippingLabel(purchaseOrderNumber)
        );
    }

}

